package com.jn.erp.web.api.course.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.erp.common.core.page.TableDataInfo;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.security.controller.BaseWebAuthController;
import com.jn.erp.utils.DateUtils;
import com.jn.erp.web.api.course.entity.TCourseOrder;
import com.jn.erp.web.api.course.entity.dto.*;
import com.jn.erp.web.api.course.entity.vo.TCourseOrderConfigVo;
import com.jn.erp.web.api.course.entity.vo.TCourseOrderVo;
import com.jn.erp.web.api.course.service.TCourseOrderService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wyp
 * @since 2024-09-04
 */
@RestController
@RequestMapping("/tCourseOrder")
public class TCourseOrderController  extends BaseWebAuthController {
    @Autowired
    private TCourseOrderService tCourseOrderService;


    /**
     * 点名情况
     * */
    @GetMapping("/orderList")
    public TableDataInfo orderList(TCourseOrderVo tCourseOrderVo) {
        startPage();
        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );
        List<TCourseOrderDto> list = tCourseOrderService.courseOrderList(tCourseOrderVo);
        return getDataTable(list);
    }


    // 课次列表
    @GetMapping("/orderFilterList")
    public TableDataInfo orderFilterList(TCourseOrderVo tCourseOrderVo) {
        startPage();
        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );
        List<TCourseOrderDto> list = tCourseOrderService.orderFilterList(tCourseOrderVo);
        return getDataTable(list);
    }


    //导出--点名情况
    @RequestMapping("/exportOrderList")
    public void exportOrderList(@RequestBody TCourseOrderVo tCourseOrderVo, HttpServletResponse response){
        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );
        //1.查询数据
        List<StudentOrderListExcalDto> studentOrderListExcalDtos = tCourseOrderService.exportOrderList(tCourseOrderVo);
        AtomicInteger i = new AtomicInteger(1);

        //2.封装成表格
        //参数1：表格标题，参数2：sheet名称
        ExportParams exportParams = new ExportParams(null, "点名情况");


        //参数1：表格参数  参数2：实体类  参数3：数据
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, StudentOrderListExcalDto.class, studentOrderListExcalDtos);
        //3.返回表格
        //设置表格文件名字
        String fileName = "点名情况";
        try {
            fileName = URLEncoder.encode(fileName, "UTF8");
            //设置返回数据类型
            response.setHeader("Access-Control-Expose-Headers", "content-disposition");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            //将表格输出
            OutputStream os = response.getOutputStream();
            sheets.write(os);
            os.close();
            os.flush();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 点名情况详情
     * */
    @PostMapping("/orderGetById")
    public AjaxResult orderGetById(@RequestBody TCourseOrderVo tCourseOrderVo) {


        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );

        TCourseOrderDto tCourseOrderDto= tCourseOrderService.getCourseOrderById(tCourseOrderVo);
        return AjaxResult.success(tCourseOrderDto);
    }

    /**
     * 点名情况详情内学员列表
     * */
    @GetMapping("/orderStudentList")
    public TableDataInfo orderStudentList(TCourseOrderVo tCourseOrderVo) {

        startPage();
        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );

        List<TCourseOrderDto> tCourseOrderDtos= tCourseOrderService.orderStudentList(tCourseOrderVo);
        return getDataTable(tCourseOrderDtos);
    }


    /**
     *  课程记录删除
     * */
    @PostMapping("/deleteOrder")
    public AjaxResult delete(@RequestBody TCourseOrderVo tCourseOrderVo) {
        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setUpdateUser(String.valueOf(getUserId()) );
        tCourseOrderVo.setUpdateDate(LocalDateTime.now() );
        tCourseOrderVo.setIsDelete("1");
        if(!Objects.isNull(tCourseOrderVo.getOrderNo())) {
            tCourseOrderService.update(tCourseOrderVo,new QueryWrapper<TCourseOrder>().eq("order_no",tCourseOrderVo.getOrderNo()));
        }else if(!Objects.isNull(tCourseOrderVo.getId())){
            tCourseOrderService.updateById(tCourseOrderVo);
        }

        return AjaxResult.success("S200");
    }

    /**
     *  点名记录修改
     * */
    @PostMapping("/updateBatchOrder")
    public AjaxResult updateBatchOrder(@RequestBody List<TCourseOrder> tCourseOrders) {
        tCourseOrders.stream().forEach(u->{
            //机构id
            u.setOrgId(Long.parseLong(loginDeptAuth()) );
            //当前登录人id
            u.setUpdateUser(String.valueOf(getUserId()) );
            u.setUpdateDate(LocalDateTime.now() );
            u.setCallTime(LocalDateTime.now() );
        });
        String code = tCourseOrderService.updateBatchOrder(tCourseOrders);

        return AjaxResult.success(code);
    }

    /**
     *  点名记录修改--标记已补
     * */
    @PostMapping("/updateOrderById")
    public AjaxResult updateOrderById(@RequestBody TCourseOrder tCourseOrder) {

        //机构id
        tCourseOrder.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrder.setUpdateUser(String.valueOf(getUserId()) );
        tCourseOrder.setUpdateDate(LocalDateTime.now() );

       String code = tCourseOrderService.updateOrderById(tCourseOrder);

        return AjaxResult.success(code);
    }
    /**
     *  课程记录修改
     * */
    @PostMapping("/updateOrder")
    public AjaxResult update(@RequestBody TCourseOrder tCourseOrder) {
        if (tCourseOrder.getClassDates() != null) {
            LocalDateTime localDateTime = DateUtils.getLocalDateTime(tCourseOrder.getClassDates(), "yyyy-MM-dd'T'HH:mm:ss.SSS");
            tCourseOrder.setClassDate(localDateTime);
        }
        tCourseOrder.setCourseId(null);
        boolean b = tCourseOrderService.update(tCourseOrder,new QueryWrapper<TCourseOrder>().eq("order_no",tCourseOrder.getOrderNo()));

        return AjaxResult.success(b);
    }

    /**
     *  添加临时学员
     * */
    @PostMapping("/addStudent")
    public AjaxResult addStudent(@RequestBody TCourseOrderVo tCourseOrderVo) {
        String code = tCourseOrderService.addStudent(tCourseOrderVo);
        return AjaxResult.success(code);
    }



    /**
     * 上课记录列表（缺课补课）
     * */
    @GetMapping("/orderListSecond")
    public TableDataInfo orderListSecond(TCourseOrderVo tCourseOrderVo) {

        startPage();
        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );

        List<TCourseOrderDto> tCourseOrderDtos= tCourseOrderService.orderListSecond(tCourseOrderVo);
        return getDataTable(tCourseOrderDtos);
    }


    //导出--点名情况--上课记录列表分班级学员
    @RequestMapping("/exportOrderListSecond")
    public void exportOrderListSecond(@RequestBody TCourseOrderVo tCourseOrderVo, HttpServletResponse response){
        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );
        Workbook sheets = null;
        if(StringUtils.isEmpty(tCourseOrderVo.getExportType())){
            tCourseOrderVo.setExportType("1");
        }
        switch (tCourseOrderVo.getExportType()){
            case "1" :{
                //1.查询数据
                List<StudentOrderListExcal2CDto> studentOrderListExcalDtos = tCourseOrderService.exportOrderListSecondC(tCourseOrderVo);
                AtomicInteger i = new AtomicInteger(1);

                //2.封装成表格
                //参数1：表格标题，参数2：sheet名称
                ExportParams exportParams = new ExportParams(null, "点名情况");


                //参数1：表格参数  参数2：实体类  参数3：数据
                sheets = ExcelExportUtil.exportExcel(exportParams, StudentOrderListExcal2CDto.class, studentOrderListExcalDtos);
                break;
            }
            case "2" :{
                //1.查询数据
                List<StudentOrderListExcal2SDto> studentOrderListExcalDtos = tCourseOrderService.exportOrderListSecondS(tCourseOrderVo);
                AtomicInteger i = new AtomicInteger(1);

                //2.封装成表格
                //参数1：表格标题，参数2：sheet名称
                ExportParams exportParams = new ExportParams(null, "超时未点情况");


                //参数1：表格参数  参数2：实体类  参数3：数据
                sheets = ExcelExportUtil.exportExcel(exportParams, StudentOrderListExcal2SDto.class, studentOrderListExcalDtos);
                break;
            }
            case "3" :{
                //1.查询数据
                List<TCourseOrderDto> tCourseOrderDtos = tCourseOrderService.orderListSecond(tCourseOrderVo);
                AtomicInteger i = new AtomicInteger(1);

                //2.封装成表格
                //参数1：表格标题，参数2：sheet名称
                ExportParams exportParams = new ExportParams(null, "缺课补课情况");


                //参数1：表格参数  参数2：实体类  参数3：数据
                sheets = ExcelExportUtil.exportExcel(exportParams, TCourseOrderDto.class, tCourseOrderDtos);
                break;
            }
        }

        //3.返回表格
        //设置表格文件名字
        String fileName = "点名情况";
        try {
            fileName = URLEncoder.encode(fileName, "UTF8");
            //设置返回数据类型
            response.setHeader("Access-Control-Expose-Headers", "content-disposition");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            //将表格输出
            OutputStream os = response.getOutputStream();
            sheets.write(os);
            os.close();
            os.flush();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 开班补课点名
     * */
    @PostMapping("/saveRepair")
    public AjaxResult saveRepair(@RequestBody TCourseOrderConfigVo tCourseOrderConfigVo) {

        startPage();
        //机构id
        tCourseOrderConfigVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderConfigVo.setCreateUser(String.valueOf(getUserId()) );
        tCourseOrderConfigVo.setCreateDate(LocalDateTime.now() );

        String code = tCourseOrderService.saveRepair(tCourseOrderConfigVo);
        return AjaxResult.success(code);
    }

    /**
     * 补课详情
     * */
    @PostMapping("/repairDetail")
    public AjaxResult repairDetail(@RequestBody TCourseOrderVo tCourseOrderVo) {

        startPage();
        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );
        tCourseOrderVo.setCreateDate(LocalDateTime.now() );

        List<TCourseOrderDto> tCourseOrderList = tCourseOrderService.repairDetail(tCourseOrderVo);
        return AjaxResult.success(tCourseOrderList);
    }

    /**
     * 课消列表
     * */
    @GetMapping("/orderListThird")
    public TableDataInfo orderListThird(TCourseOrderVo tCourseOrderVo) {

        startPage();
        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );

        List<TCourseOrderDto> tCourseOrderDtos= tCourseOrderService.orderListThird(tCourseOrderVo);
        return getDataTable(tCourseOrderDtos);
    }

    /**
     * 课消详情
     * */
    @PostMapping("/orderDetailSecond")
    public AjaxResult orderDetailSecond(@RequestBody TCourseOrderVo tCourseOrderVo) {


        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );

        TCourseOrderDto tCourseOrderDto= tCourseOrderService.orderDetailSecond(tCourseOrderVo);
        return AjaxResult.success(tCourseOrderDto);
    }

    /**
     * 课消详情金额
     * */
    @PostMapping("/orderCountSecond")
    public AjaxResult orderCountSecond(@RequestBody TCourseOrderVo tCourseOrderVo) {


        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );

        Map map = tCourseOrderService.orderCountSecond(tCourseOrderVo);
        return AjaxResult.success(map);
    }


    //导出--课消列表
    @RequestMapping("/exportOrderListThird")
    public void exportOrderListThird(@RequestBody TCourseOrderVo tCourseOrderVo, HttpServletResponse response){
        //机构id
        tCourseOrderVo.setOrgId(Long.parseLong(loginDeptAuth()) );
        //当前登录人id
        tCourseOrderVo.setCreateUser(String.valueOf(getUserId()) );
        Workbook sheets = null;
        if(StringUtils.isEmpty(tCourseOrderVo.getExportType())){
            tCourseOrderVo.setExportType("1");
        }
                //1.查询数据
        List<TCourseOrderDto> tCourseOrderDtos= tCourseOrderService.orderListThird(tCourseOrderVo);

        List<StudentOrderListExcal3Dto> studentOrderListExcalDtos = tCourseOrderDtos.stream().map(u->{
            StudentOrderListExcal3Dto studentOrderListExcal3Dto = new StudentOrderListExcal3Dto();
            BeanUtils.copyProperties(u,studentOrderListExcal3Dto);
            return studentOrderListExcal3Dto;
        }).collect(Collectors.toList());
        AtomicInteger i = new AtomicInteger(1);

        //2.封装成表格
        //参数1：表格标题，参数2：sheet名称
        ExportParams exportParams = new ExportParams(null, "课消列表");


        //参数1：表格参数  参数2：实体类  参数3：数据
        sheets = ExcelExportUtil.exportExcel(exportParams, StudentOrderListExcal3Dto.class, studentOrderListExcalDtos);



        //3.返回表格
        //设置表格文件名字
        String fileName = "课消列表";
        try {
            fileName = URLEncoder.encode(fileName, "UTF8");
            //设置返回数据类型
            response.setHeader("Access-Control-Expose-Headers", "content-disposition");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");

            //将表格输出
            OutputStream os = response.getOutputStream();
            sheets.write(os);
            os.close();
            os.flush();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

